from sqlalchemy.sql import func

from models import DB
from models import tag
from pkg.tools import now_timestamp

class Article(DB.Model):

    __tablename__ = "article"

    id = DB.Column(DB.Integer, primary_key=True)
    created_on = DB.Column(DB.Integer, default=now_timestamp(),  nullable=False)
    update_on = DB.Column(DB.Integer, default=created_on, server_default="0", nullable=False)
    # 定义外键
    tag_id = DB.Column(DB.Integer, DB.ForeignKey(tag.Tag.id))
    title = DB.Column(DB.String(64), nullable=False)
    author = DB.Column(DB.String(64), nullable=False)
    
    desc =  DB.Column(DB.String(255))
    content = DB.Column(DB.Text, nullable=False)




    def __repr__(self):
        return 'Tag:%s'% self.title



def add(title, author, tag_id, desc, content):
    if tag.is_exist(tag_id):
        a = Article(title=title, author=author, tag_id=tag_id,desc=desc, content=content)
        DB.session.add(a)
        DB.session.commit()
        return f"添加文章 {title} 成功"
    else:
        return "文章并没有添加，错误：tag 不存在"



def delete(id):
    a = Article.query.get(id)
    if a == None:
        return f"错误: {id} 不存在"
    DB.session.delete(a)
    DB.session.commit()
    return f"成功 {a.title} 删除"



def update(id, name, byname=None):
    t = Tag.query.get(id)
    if t == None:
        return f"错误: {id} 不存在"
    old_name = t.name

    if byname != None:
        t.byname = byname
    t.name = name

    DB.session.commit()
    return f"{old_name} 修改成功"




def get(id):
    t = Tag.query.get(id)
    if t == None:
        return f"错误: {id} 不存在"
    return t

def get_all():
    ts = Tag.query.all()
    return ts

def count():
    return Tag.query.count()

